package com.hdy.javachatroomdemo.Service;

import com.hdy.javachatroomdemo.Model.User;
import com.hdy.javachatroomdemo.Model.UserMapper;
import com.hdy.javachatroomdemo.Model.UserProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class UserService {
    //每个客户端都有不同的线程,这些用户的变量互相之间不会产生干扰
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserProperties userProperties;
    //登录和注册后续加入图形验证码的步骤
    //处理登录接口的逻辑
    public User loginGetUser(String username, String password, HttpServletRequest request) {
        User user =new User();
        //出现登录失败的几种可能
        //1.用户名为空或密码为空
        //2.用户名或者密码错误
        if(username==null||userMapper.selectByUsername(username)==null||!userMapper.selectByUsername(username)
                .getPassword().equals(password)){
            return user;
        }
        //登陆成功,创建会话,返回user
        //有会话就保持不变,没有回话要创建一个新的会话
        HttpSession session=request.getSession(true);
        //验证登录是否正确
        user = userMapper.selectByUsername(username);
        user.setPassword("");
        session.setAttribute(userProperties.getSession().getKey(),user);
        return user;
    }

    //处理注册接口的逻辑
    public User registerGetUser(String username, String password) {
        User user =new User();
        //注册失败的原因
        //1.用户名已经存在
        //这里采用try catch的方式,让数据库在插入数据的时候报错从而触发catch里面的逻辑
        try{
            user.setUsername(username);
            user.setPassword(password);
            int ret=userMapper.insert(user);
            log.info("数据库插入影响行数:"+ret);
        }
        catch (DuplicateKeyException e){
            log.info("注册失败: username="+username);
//            e.printStackTrace();
            //注册失败,返回空白的对象
            user =new User();
        }
        user.setPassword("");
        return user;
    }
}
